package com.im.service.fixAsset.smo;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.im.MDA;
import com.im.service.dto.FixAsset;
import com.im.service.dto.FundPlan;
import com.im.service.dto.FundSource;
import com.im.service.dto.ImplementProject;
import com.im.service.dto.InvestPlan;
import com.im.service.dto.PageQuery;
import com.im.service.dto.ProjStats;
import com.im.service.fixAsset.dao.IFixAssetQueryDao;
import com.im.service.fundPlan.dao.IFundPlanQueryDAO;
import com.im.service.investPlan.dao.IInvestPlanQueryDAO;
import com.im.service.projectInfo.dao.IFundSourceQueryDAO;
import com.im.util.JsonUtil;
import com.im.util.ListUtil;
import com.im.util.StringUtil;
import com.im.viewmodel.fixAsset.FixAssetRspVo;
import com.im.viewmodel.fixAsset.YearDtListRspVo;
import com.im.viewmodel.fundPlan.FundDetailVo;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class IFixAssetQuerySmoImpl implements IFixAssetQuerySmo {

    @Autowired
    private IFundSourceQueryDAO fundSourceQueryDAO;
    @Autowired
    private IFundPlanQueryDAO fundPlanQueryDAO;
    @Autowired
    private IFixAssetQueryDao fixAssetQueryDao;
    @Autowired
    private IInvestPlanQueryDAO investPlanQueryDAO;

    @Override
    public PageQuery<FixAssetRspVo> queryFixAssetListForUI(String inJson, List<String> typelist) throws Exception{
        PageQuery<FixAssetRspVo> page = JsonUtil.jsonToBean(inJson, PageQuery.class);
        PageHelper.startPage(page.getPageNumber(), page.getPageSize());
        List<FixAssetRspVo> ls = new ArrayList<FixAssetRspVo>();
        String yearDt =  JsonUtil.obtainValueFromJsonObject(inJson,"year");
        String impleProjId = JsonUtil.obtainValueFromJsonObject(inJson,"impleProjId");
        String developOrg = JsonUtil.obtainValueFromJsonObject(inJson,"developOrg");
        String planType = JsonUtil.obtainValueFromJsonObject(inJson,"planType");

        Map<String, Object> param = new HashMap<String, Object>();
        FixAsset fa = new FixAsset();
        fa.setYearDt(yearDt);
        fa.setImpleProjId(impleProjId);
        fa.setOrgId(developOrg);
        fa.setPlanType(planType);

        param.put("fixAsset", fa);
        param.put("page", page);
        List<FixAsset> fixAssets = fixAssetQueryDao.queryFixAssetList(param);
        for (FixAsset fixAsset : fixAssets) {
            // 概算+三项累计查询
            List<FundDetailVo> fundDetailVos = queryFourFundSource(fixAsset.getImpleProjId(), fixAsset.getFixAssetId(), fixAsset.getYearDt());
            FixAssetRspVo vo = new FixAssetRspVo();
            BeanUtils.copyProperties(fixAsset,vo);
            vo.setFundDetailVo(fundDetailVos);
            ls.add(vo);
        }

        // 2.3获取纵向统计资金
        List<Map<String,Object>> statsList = null;
        if(fixAssets != null && fixAssets.size() > 0){
            statsList = fixAssetQueryDao.queryFixAssetFoundSourceStats(fixAssets);
        }
        double buTotal = 0.0;//部补助
        double shengTotal = 0.0;//省财政
        double gaoTotal = 0.0;//高速水运融资
        double shiTotal = 0.0;//市州配套
        double qiTotal = 0.0;//企业自筹
        if(statsList != null && statsList.size() > 0){
            for(Map<String,Object> map : statsList){
                if(map.get("fundSourceType").toString().equals(MDA.FUND_SOURCE_TYPE_BU)){
                    buTotal = Double.parseDouble(map.get("total").toString());
                }
                if(map.get("fundSourceType").toString().equals(MDA.FUND_SOURCE_TYPE_SHENG)){
                    shengTotal = Double.parseDouble(map.get("total").toString());
                }
                if(map.get("fundSourceType").toString().equals(MDA.FUND_SOURCE_TYPE_GAO)){
                    gaoTotal =Double.parseDouble(map.get("total").toString());
                }
                if(map.get("fundSourceType").toString().equals(MDA.FUND_SOURCE_TYPE_SHI)){
                    shiTotal =Double.parseDouble(map.get("total").toString());
                }
                if(map.get("fundSourceType").toString().equals(MDA.FUND_SOURCE_TYPE_QI)){
                    qiTotal =Double.parseDouble(map.get("total").toString());
                }
            }
        }
        double allTotal = (double)Math.round((buTotal + shengTotal + gaoTotal + shiTotal + qiTotal)*100)/100;;

        List<ProjStats> fixAssetStatsList = new ArrayList<ProjStats>();
        ProjStats stats = new ProjStats();
        stats.setFundSourceBu(buTotal);
        stats.setFundSourceGao(gaoTotal);
        stats.setFundSourceQi(qiTotal);
        stats.setFundSourceShi(shiTotal);
        stats.setFundSourceSheng(shengTotal);
        stats.setTotal(allTotal);
        stats.setLinkmanName("合计:");
        fixAssetStatsList.add(stats);
        PageInfo pageInfo = new PageInfo(ls);
        page.setRows(ls);
        page.setFooter(fixAssetStatsList);
        page.setTotalPages(pageInfo.getPages());
        page.setTotal(pageInfo.getTotal());
        return page;

    }

    @Override
    public YearDtListRspVo queryFixAssetYearDtList(String inJson, List<String> typelist) throws Exception{
        YearDtListRspVo ls = new YearDtListRspVo();
        List<String> statusCds = new ArrayList<String>();
        Map<String, Object> param = new HashMap<String, Object>();
        List<String> faStatusCds = fixAssetQueryDao.queryFixAssetYearDtList(param);
        for (String faStatusCd : faStatusCds) {
            if(!statusCds.contains(faStatusCd)){
                statusCds.add(faStatusCd);
            }
        }
        ls.setStatusCds(statusCds);
        return ls;
    }

    /**
     *
     * @param impleProjId:实施项目Id
     * @param fundSourceObjId:固定资产ID
     * @param yearDt:累计至****年
     * @return
     */
    private List<FundDetailVo> queryFourFundSource(String impleProjId, String fundSourceObjId, String yearDt) {
        List<FundDetailVo> fundDetailVos = new ArrayList<FundDetailVo>();

        // 1、概算总投资 实施项目资金
        List<String> objIds = new ArrayList<String>();
        objIds.add(impleProjId);
        FundDetailVo planProjMoney = getEachMoney(MDA.FUND_SOURCE_OBJ_TYPE_IMPLEMENT, objIds, null, null, "10");
        planProjMoney.setType("planProjMoney");
        fundDetailVos.add(planProjMoney);

        // 2、累计至****年下达计划 实施项目 批复与下达后 各项资金统计；（如：累计2017，包括2017申报批次，2016年申报批次，2015年申报批次 累计 实施项目各个批次批复与下达完后的各项资金统计 ）。
        objIds.clear();
        Map<String, Object> param = new HashMap<String, Object>();
        InvestPlan ip = new InvestPlan();
        ip.setImpleProjId(impleProjId);
        ip.setStatusCd("60");
        ip.setYearDt(yearDt);
        param.put("investPlan", ip);
        param.put("fundSourceObjId",fundSourceObjId);
        List<InvestPlan> ips = investPlanQueryDAO.queryInvestPlanList(param);
        if (!ListUtil.isListEmpty(ips)) {
            for (InvestPlan o : ips) {
                if (o.getInvestPlanId() != null && o.getInvestPlanId().equals(fundSourceObjId)) {
                    continue;
                }
                objIds.add(o.getInvestPlanId());
            }
        }
        FundDetailVo implProjMoney = getEachMoney(MDA.FUND_SOURCE_OBJ_TYPE_INVEST_303, objIds, null, null, "10");
        implProjMoney.setType("implProjMoney");
        fundDetailVos.add(implProjMoney);

        // 3、累计至****年完成投资 实施项目 在 固定资产中录入后 各项资金统计
        objIds.clear();
        FixAsset fa = new FixAsset();
        fa.setImpleProjId(impleProjId);
        param.put("fixAsset", fa);
        param.put("fundSourceObjId",fundSourceObjId);
        List<FixAsset> fixAssets = fixAssetQueryDao.queryFixAssetList(param);
        for (FixAsset fixAsset : fixAssets) {
            objIds.add(fixAsset.getFixAssetId());
        }
        FundDetailVo investPlanMoney = getEachMoney(MDA.FUND_SOURCE_OBJ_TYPE_FUND_501, objIds, null, null, "10");
        investPlanMoney.setType("investPlanMoney");
        fundDetailVos.add(investPlanMoney);

        // 4 本次完成投资 固定资产对应的各项资金统计
        FundDetailVo fundPlanMoney = new FundDetailVo();
        objIds.clear();
        param.clear();
        FixAsset fas = new FixAsset();
        fas.setImpleProjId(impleProjId);
        param.put("fixAsset", fas);
        List<FixAsset> fixAssetss = fixAssetQueryDao.queryFixAssetList(param);
        for (FixAsset fixAsset : fixAssetss) {
            objIds.add(fixAsset.getFixAssetId());
        }
        fundPlanMoney = getEachMoney(MDA.FUND_SOURCE_OBJ_TYPE_FUND_501, objIds, null, null, "10");
        fundPlanMoney.setType("fundPlanMoney");
        fundDetailVos.add(fundPlanMoney);
        return fundDetailVos;
    }

    public FundDetailVo getEachMoney(String objType,List<String> objIds,String beginYear,String endYear,String statusCd){
        FundDetailVo vo = new FundDetailVo();
        vo.setFundBu("0");
        vo.setFundSheng("0");
        vo.setFundGao("0");
        vo.setFundShi("0");
        vo.setFundQi("0");
        vo.setFundOther("0");
        vo.setTotal("0");
        if(objIds == null || objIds.size() == 0){
            return vo;
        }
        Map<String,Object> inMap = new HashMap<String,Object>();
        inMap.put("objType",objType);
        inMap.put("objIds",objIds);
        inMap.put("statusCd",statusCd);
        if(beginYear!=null){
            inMap.put("beginYear",beginYear);
        }
        inMap.put("endYear",endYear);
        List<FundSource> fundSourceList = fundSourceQueryDAO.queryFundsDetailByParam(inMap);
        BigDecimal total = new BigDecimal(0);
        BigDecimal buSum = new BigDecimal(0);
        BigDecimal shengSum = new BigDecimal(0);
        BigDecimal gaoSum = new BigDecimal(0);
        BigDecimal shiSum = new BigDecimal(0);
        BigDecimal qiSum = new BigDecimal(0);
        BigDecimal otherSum = new BigDecimal(0);

        for(FundSource fs : fundSourceList) {
            switch (fs.getFundSourceType()) {
                case "10":
                    buSum = buSum.add(new BigDecimal(fs.getFundVal()).setScale(2, BigDecimal.ROUND_HALF_UP));
                    break;
                case "20":
                    shengSum = shengSum.add(new BigDecimal(fs.getFundVal()).setScale(2, BigDecimal.ROUND_HALF_UP));
                    break;
                case "30":
                    gaoSum = gaoSum.add(new BigDecimal(fs.getFundVal()).setScale(2, BigDecimal.ROUND_HALF_UP));
                    break;
                case "40":
                    shiSum = shiSum.add(new BigDecimal(fs.getFundVal()).setScale(2, BigDecimal.ROUND_HALF_UP));
                    break;
                case "50":
                    qiSum = qiSum.add(new BigDecimal(fs.getFundVal()).setScale(2, BigDecimal.ROUND_HALF_UP));
                    break;
                case "60":
                    otherSum = otherSum.add(new BigDecimal(fs.getFundVal()).setScale(2, BigDecimal.ROUND_HALF_UP));
                    break;
                default:
                    break;
            }
        }
        total = total.add(buSum).add(shengSum).add(gaoSum).add(shiSum).add(qiSum).add(otherSum);
        vo.setFundBu(buSum.toPlainString());
        vo.setFundSheng(shengSum.toPlainString());
        vo.setFundGao(gaoSum.toPlainString());
        vo.setFundShi(shiSum.toPlainString());
        vo.setFundQi(qiSum.toPlainString());
        vo.setFundOther(otherSum.toPlainString());
        vo.setTotal(total.toPlainString());
        return vo;
    }

}
